﻿using java.security.interfaces;
using jieyi.tools.algorithmic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ToolsFromJY
{
    /// <summary>
    /// 文件加解密帮助类，封装捷羿提供的Demo
    /// </summary>
    public class FileEncryptDecryptHelper
    {
        /// <summary>
        /// 解密,如果发生异常则返回解密失败且strAfterDecrypt字段填充异常信息
        /// </summary>
        /// <param name="modulus">公钥系数</param>
        /// <param name="exponentPri">私钥系数</param>
        /// <param name="exponentPub">指数大小</param>
        /// <param name="strToDecrypt">待解密字符串</param>
        /// <param name="strAfterDecrypt">解密得到明文字符串</param>
        /// <returns></returns>
        public static bool Decrypt(string modulus, string exponentPri, string exponentPub, string strToDecrypt, out string strAfterDecrypt)
        {
            bool isDecryptSuccess = false;
            strAfterDecrypt = "";
            try
            {
                string input = strToDecrypt;
                RSAPublicKey rsaPublicKey = RSAUtil.loadPublicKey(modulus, exponentPub, 16);
                RSAPrivateKey rsaPrivateKey = RSAUtil.loadPrivateKey(modulus, exponentPri, 16);

                strAfterDecrypt = RSAASCIIUtil.publicKeyDecrypt("RSA", "ECB", "PKCS1Padding", rsaPublicKey, input, "UTF-8");
                isDecryptSuccess = true;
            }
            catch(Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                isDecryptSuccess = false;
                strAfterDecrypt = ex.ToString();
            }
            return isDecryptSuccess;
        }

        /// <summary>
        /// 加密,如果发生异常则返回加密失败且strAfterEncrypt字段填充异常信息
        /// </summary>
        /// <param name="modulus">公钥系数</param>
        /// <param name="exponentPri">私钥系数</param>
        /// <param name="exponentPub">指数大小</param>
        /// <param name="strToDecrypt"></param>
        /// <param name="strAfterDecrypt"></param>
        /// <returns></returns>
        public static bool Encrypt(string modulus, string exponentPri, string exponentPub, string strToDecrypt, out string strAfterEncrypt)
        {
            bool isEncryptSuccess = false;
            strAfterEncrypt = "";
            try
            {
                string input = strToDecrypt;
                RSAPublicKey rsaPublicKey = RSAUtil.loadPublicKey(modulus, exponentPub, 16);
                RSAPrivateKey rsaPrivateKey = RSAUtil.loadPrivateKey(modulus, exponentPri, 16);

                strAfterEncrypt = RSAASCIIUtil.privateKeyEncrypt("RSA", "ECB", "PKCS1Padding", rsaPrivateKey, input, "UTF-8");
                strAfterEncrypt = strAfterEncrypt.ToUpper();
                isEncryptSuccess = true;
            }
            catch (Exception ex)
            {
                isEncryptSuccess = false;
                strAfterEncrypt = ex.ToString();
            }
            return isEncryptSuccess;
        }
    }
}
